package marlon.smsbatcheditor.activity;

import java.util.List;

import marlon.smsbatcheditor.Constants;
import marlon.smsbatcheditor.R;
import marlon.smsbatcheditor.db.RuleDAO;
import marlon.smsbatcheditor.db.SmsDAO;
import marlon.smsbatcheditor.model.Rule;
import marlon.smsbatcheditor.model.Sms;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View.OnClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.AdapterContextMenuInfo;

/**
 * 
 * @author marlonyao<yaolei135@gmail.com>
 */
public class RuleListActivity extends ListActivity implements OnClickListener {
	private ListView lvRules;
	private TextView tvCreateRule;
	
	private List<Rule> rules;
	private RuleDAO ruleDAO;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.rule_list);
        
        lvRules = getListView();
        tvCreateRule = (TextView) findViewById(R.id.tvCreateRule);
        tvCreateRule.setOnClickListener(this);
        
        ruleDAO = new RuleDAO(this);
        rules = ruleDAO.findAll();
        lvRules.setAdapter(new RulesAdapter(this, rules));
        
        registerForContextMenu(lvRules);
    }
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	super.onCreateOptionsMenu(menu);
    	menu.add(0, Constants.MENU_CREATE_RULE, Menu.NONE, "Create Rule");
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case Constants.MENU_CREATE_RULE:
        	createRule();
        	return true;
        default:
            return super.onOptionsItemSelected(item);
        }
    }

	private void createRule() {
		Intent intent = new Intent(this, EditRuleActivity.class);
		intent.setAction(Intent.ACTION_INSERT);
		startActivityForResult(intent, 0);
	}

	@Override
	public void onClick(View v) {
		if (v == tvCreateRule) {
			createRule();
		}
	}
	
    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
    	super.onCreateContextMenu(menu, v, menuInfo);
    	if (v == lvRules) {
    		menu.add(0, Constants.MENU_EDIT_RULE, 0, "Edit");
    		menu.add(0, Constants.MENU_REMOVE_RULE, 0, "Remove");
    		menu.add(1, Constants.MENU_PREVIEW_RULE, 0, "Preview");
    		menu.add(1, Constants.MENU_EXEC_RULE, 0, "Apply");
    	}
	}

    @Override
	public boolean onContextItemSelected(final MenuItem item) {
       	switch (item.getItemId()) {
       	case Constants.MENU_EDIT_RULE:
       		AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
       		Intent intent = new Intent(this, EditRuleActivity.class);
       		intent.setAction(Intent.ACTION_EDIT);
       		intent.putExtra("rule_id", rules.get(menuInfo.position).getId());
       		startActivityForResult(intent, 0);
       		return true;
       	case Constants.MENU_REMOVE_RULE:
       		AlertDialog.Builder builer = new AlertDialog.Builder(this);
       		builer.setMessage("Are you sure to remove this rule?")
       			.setCancelable(false)
       			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
			       		Rule rule = rules.get(menuInfo.position);
			       		if (ruleDAO.remove(rule.getId())) {
			       			rules.remove(menuInfo.position);
			       			lvRules.setAdapter(new RulesAdapter(RuleListActivity.this, rules));
			       		}
					}
				}).setNegativeButton("No", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
       		builer.create().show();
       		return true;
       	case Constants.MENU_PREVIEW_RULE:
       		menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
       		intent = new Intent(this, PreviewActivity.class);
       		intent.putExtra("rule_id", rules.get(menuInfo.position).getId());
       		startActivity(intent);
       		return true;
       	case Constants.MENU_EXEC_RULE:
       		builer = new AlertDialog.Builder(this);
       		builer.setMessage("Are you sure to apply this rule immediately?")
       			.setCancelable(false)
       			.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						AdapterContextMenuInfo menuInfo = (AdapterContextMenuInfo) item.getMenuInfo();
			       		applyRule(rules.get(menuInfo.position));
					}
				}).setNegativeButton("No", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				});
       		builer.create().show();
       		return true;
       	default:
       		return super.onOptionsItemSelected(item);
       	}
	}

	private void applyRule(Rule rule) {
		SmsDAO smsDAO = new SmsDAO(this);
		Cursor cursor = smsDAO.find(rule);
		int count = 0;
		if (cursor.moveToFirst()) {
			do {
				Sms sms = new Sms(cursor);
				if (smsDAO.update(sms, rule))
					++count;
			} while (cursor.moveToNext());
		}
		if (count > 0)
			Toast.makeText(this, "Updated " + count + " SMS(es)", Toast.LENGTH_SHORT).show();
		else
			Toast.makeText(this, "Updated no SMS(es)", Toast.LENGTH_SHORT).show();
	}
    
    @Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	if (resultCode == RESULT_OK) {
    		// reload rules
    		rules = ruleDAO.findAll();
            lvRules.setAdapter(new RulesAdapter(this, rules));
    	}
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		Intent intent = new Intent(this, PreviewActivity.class);
   		intent.putExtra("rule_id", rules.get(position).getId());
   		startActivity(intent);
	}
}
